package com.smartum.mpr.dao;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.smartum.mpr.model.Item;
import com.smartum.mpr.model.Job;

@Repository
public class ItemDao extends GenericDao<Long, Item> {

	
	@Override
	protected Class<Item> getEntityClass() {
		return Item.class;
	}

	public List<Item> getUserItems(Long userId, long timestamp, int amount) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Item.class);
		criteria.addOrder(Order.desc("timeStamp"));
		if (timestamp == 0) {
			criteria.add(Restrictions.gt("timeStamp", timestamp)).createCriteria("owner")
			        .add(Restrictions.eq("id", userId));
		} else {
			criteria.add(Restrictions.lt("timeStamp", timestamp)).createCriteria("owner")
			        .add(Restrictions.eq("id", userId));

		}

		List<Item> items = hibernateTemplate.findByCriteria(criteria, 0, amount);
		return items;
	}
	
	public List<Item> getUserItems(long userId) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Item.class);
		criteria.createCriteria("owner").add(Restrictions.eq("id", userId));
		return hibernateTemplate.findByCriteria(criteria);
	}


	public List<Item> getItemsBySearchQuery(Long categoryId, Long subCategoryId, Boolean getHeighest, Long timestamp,
	        int amount, Long countyId) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Item.class);

		criteria.createAlias("subCategory", "subCategory");

		if (categoryId != null) {
			criteria.createCriteria("subCategory.category").add(Restrictions.eq("id", categoryId));
		}

		if (subCategoryId != null) {
			criteria.add(Restrictions.eq("subCategory.id", subCategoryId));
		}

		if (countyId != null) {
			criteria.createCriteria("county").add(Restrictions.eq("id", countyId));
		}

		if (getHeighest != null) {
			if (getHeighest) {
				criteria.addOrder(Order.desc("price"));
			} else {
				criteria.addOrder(Order.asc("price"));
			}
		}else{
			criteria.addOrder(Order.desc("timeStamp"));
		}

		if (timestamp == 0) {
			criteria.add(Restrictions.gt("timeStamp", timestamp));
		} else {
			criteria.add(Restrictions.lt("timeStamp", timestamp));

		}
		
		List<Item> items =  hibernateTemplate.findByCriteria(criteria, 0, amount);
		return items;
	}

}
